package org.jeecg.modules.jd.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.Date.DateUtil;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.constant.TaskNamesConstant;
import org.jeecg.modules.appuser.entity.TbUserVip;
import org.jeecg.modules.appuser.entity.TbUserWallet;
import org.jeecg.modules.appuser.entity.TbUserWalletDetail;
import org.jeecg.modules.appuser.service.ITbUserIntegralService;
import org.jeecg.modules.appuser.service.ITbUserVipService;
import org.jeecg.modules.appuser.service.ITbUserWalletDetailService;
import org.jeecg.modules.appuser.service.ITbUserWalletService;
import org.jeecg.modules.jd.entity.JD_order;
import org.jeecg.modules.jd.entity.JD_order_sku;
import org.jeecg.modules.jd.entity.JD_position;
import org.jeecg.modules.jd.mapper.JD_orderMapper;
import org.jeecg.modules.jd.service.IJD_orderService;
import org.jeecg.modules.jd.service.IJD_order_skuService;
import org.jeecg.modules.jd.service.IJD_positionService;
import org.jeecg.modules.jd.util.JDContants;
import org.jeecg.modules.jd.util.JDOrderRequest;
import org.jeecg.modules.jd.util.JDOrderUtil;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @Description: 京东订单
 * @Author: jeecg-boot
 * @Date: 2020-06-11
 * @Version: V1.0
 */
@Service
@Slf4j
public class JD_orderServiceImpl extends ServiceImpl<JD_orderMapper, JD_order> implements IJD_orderService {

    @Autowired
    private ITbUserIntegralService tbUserIntegralService;
    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private ITbUserVipService tbUserVipService;

    @Autowired
    private ITbUserWalletService tbUserWalletService;

    @Autowired
    private ITbUserWalletDetailService tbUserWalletDetailService;
    @Autowired
    private IJD_positionService jD_positionService;
    @Autowired
    @Lazy(true)
    private ITbMnUserService tbMnUserService;

    @Autowired
    private IJD_order_skuService jD_order_skuService;

    /**
     * 更新订单，并返佣
     *
     * @param parameter
     */
    public void updateOrderData(String parameter) {
        //得到默认配置的时间
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("order_start_time");
        String daynum = "0";
        if (null != dictModelList && dictModelList.size() > 0) {
            daynum = dictModelList.get(0).getValue();
        }
        JDOrderRequest jdOrderRequest = new JDOrderRequest();
        jdOrderRequest.setPageNo(JDContants.order_pageNo);
        jdOrderRequest.setPageSize(JDContants.order_pageSize);
        //yyyyMMddHHmm
        if (!StringUtils.isEmpty(parameter)) {
            daynum = parameter;
        }
        String jdtime = DateUtil.getJDBeforeDate(Integer.valueOf(daynum));
        jdOrderRequest.setTime(jdtime);
        //type 订单时间查询类型(1：下单时间，2：完成时间，3：更新时间)
        jdOrderRequest.setType(1);
        List<JD_order> jd_orderList = JDOrderUtil.getOrders(jdOrderRequest);
        if (null != jd_orderList && jd_orderList.size() > 0) {
            for (JD_order jd_order : jd_orderList) {
                Long order_id = jd_order.getOrderId();
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("order_id", order_id);
                JD_order old_jd_order = this.getOne(queryWrapper);
                String skugoods = jd_order.getSkuList();
                List<JD_order_sku> jd_positionList = JSON.parseArray(skugoods, JD_order_sku.class);
                if (null == old_jd_order) {
                    //保存订单
                    for (JD_order_sku jd_order_sku : jd_positionList) {
                        jd_order_sku.setOrderId(jd_order.getOrderId());
                        jd_order_sku.setRebateStatus(0);
                        jD_order_skuService.save(jd_order_sku);
                    }
                    this.save(jd_order);
                } else {
                    //编辑订单
                    for (JD_order_sku jd_order_sku : jd_positionList) {
                        jd_order_sku.setOrderId(jd_order.getOrderId());
                        QueryWrapper orderskuQueryWrapper = new QueryWrapper();
                        orderskuQueryWrapper.eq("order_id", jd_order_sku.getOrderId());
                        JD_order_sku jd_order_sku1 = jD_order_skuService.getOne(orderskuQueryWrapper);
                        updateWalletData(jd_order_sku1, orderskuQueryWrapper);
                    }
                }
            }

        }

    }

    private void updateWalletData(JD_order_sku jd_order_sku, QueryWrapper orderskuQueryWrapper) {
        if (jd_order_sku.getValidCode() == 18) {

            String pid = jd_order_sku.getPid();
            JD_position jd_position = jD_positionService.getById(pid);
            TbMnUser tbMnUser = tbMnUserService.getById(jd_position.getUserId());

            if (null == jd_order_sku.getRebateStatus() || jd_order_sku.getRebateStatus() == 0) {
                jd_order_sku.setRebateStatus(1);
                int rebate_layer_num = 3;
                RebateUser(jd_order_sku, tbMnUser, rebate_layer_num);
                //  增加个人积分一次
                Map<String, Object> resultData1 = tbUserIntegralService.doActionTask(tbMnUser.getId(), TaskNamesConstant.Task_SELF_PURCHASE_GOODS);
                log.info("京东增加个人积分一次--->" + resultData1.toString());

            }
        }
        jD_order_skuService.update(jd_order_sku, orderskuQueryWrapper);

    }

    //升级用户等级
    private boolean upgradeUserGrade(TbMnUser tbMnUser) {

        BigDecimal profit = new BigDecimal(0);
        if (null != tbMnUser) {
            QueryWrapper userWalletQueryWrapper = new QueryWrapper();
            userWalletQueryWrapper.eq("user_id", tbMnUser.getId());
            userWalletQueryWrapper.eq("pay_from", PayTypeConstant.PAYFORM_REBATE);
            List<TbUserWalletDetail> tbUserWalletDetailList = tbUserWalletDetailService.list(userWalletQueryWrapper);
            if (null != tbUserWalletDetailList && tbUserWalletDetailList.size() > 0) {
                for (TbUserWalletDetail tbUserWalletDetail : tbUserWalletDetailList) {
                    profit = profit.add(tbUserWalletDetail.getPayNumber());
                }

            }
            log.info(tbMnUser.getPhone() + "用户升级---------------------------------->" + profit);
            //得到上一等级
            TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
            int next_srot = tbUserVip.getSort() + 1;
            QueryWrapper vipQueryWrapper = new QueryWrapper();
            vipQueryWrapper.eq("sort", next_srot);
            TbUserVip next_tbUserVip = tbUserVipService.getOne(vipQueryWrapper);
            if (null == next_tbUserVip) {
                log.info("你已经是最高等级了");
            } else {

                BigDecimal next_tbUserVipBalanceMin = next_tbUserVip.getInviteProfit();
                log.info(tbMnUser.getPhone() + "用户升级------profit.compareTo(next_tbUserVipBalanceMin---->" + profit.compareTo(next_tbUserVipBalanceMin));
                if (profit.compareTo(next_tbUserVipBalanceMin) >= 0) {
                    //升级
                    tbMnUser.setVipId(next_tbUserVip.getId());
                    tbMnUser.setVipName(next_tbUserVip.getVipName());
                    String bigDecimal = next_tbUserVip.getFirstRebate().multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
                    tbMnUser.setOwnRate(bigDecimal);
                    tbMnUserService.updateById(tbMnUser);
                    log.info(tbMnUser.getPhone() + "用户升级---------完成------------------------->\n");
                    log.info("{}升级成功,手机号码{}", tbMnUser.getAccount(), tbMnUser.getPhone());
                    return true;
                }
            }
        }

        return false;
    }

    private void RebateUser(JD_order_sku jd_order_sku, TbMnUser tbMnUser, Integer rebate_layer_num) {

        if (rebate_layer_num > 0) {
            if (null != tbMnUser) {
                //查询它的被邀请人,进行返佣

                TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
                BigDecimal firstRebate = null;
                if (rebate_layer_num == 3) {
                    firstRebate = tbUserVip.getFirstRebate();
                }
                if (rebate_layer_num == 2) {
                    firstRebate = tbUserVip.getSecondRebate();
                }
                if (rebate_layer_num == 1) {
                    firstRebate = tbUserVip.getThirdRebate();
                }
                BigDecimal actualCosPrice = jd_order_sku.getActualCosPrice();
                BigDecimal upperFirstFee = firstRebate.multiply(actualCosPrice);
                if (upperFirstFee.compareTo(new BigDecimal(0)) > 0) {
                    TbUserWallet tbUserWallet = tbUserWalletService.getOneByUser_id(tbMnUser.getId());
                    synchronized (tbUserWallet) {
                        BigDecimal upperFirstWalletBalance = tbUserWallet.getBalance();
                        BigDecimal new_upperFirstWalletBalance = upperFirstWalletBalance.add(upperFirstFee);
                        tbUserWallet.setBalance(new_upperFirstWalletBalance);

                        if (saveUserWalletDetail(tbUserWallet, upperFirstFee, tbMnUser.getId())) {
                            //资产更新成功
                            if (tbUserWalletService.updateById(tbUserWallet)) {
                                rebate_layer_num = rebate_layer_num - 1;
                                TbMnUser inviteesUpperFirst = tbMnUserService.getInviteesUpperFirst(tbMnUser);
                                //得到用户等级
                                if (null != inviteesUpperFirst) {
                                    RebateUser(jd_order_sku, inviteesUpperFirst, rebate_layer_num);
                                }
                            }
                        }
                    }
                }
            }
            //用户升级
            upgradeUserGrade(tbMnUser);
        }
    }

    private boolean saveUserWalletDetail(TbUserWallet tbUserWallet, BigDecimal newBalance, String fromUserId) {
        TbUserWalletDetail tbUserWalletDetail = new TbUserWalletDetail();
        tbUserWalletDetail.setPayFrom(PayTypeConstant.PAYFORM_REBATE);
        tbUserWalletDetail.setPayType(PayTypeConstant.PAYTYPE_INCOME);
        tbUserWalletDetail.setPayNumber(newBalance);
        tbUserWalletDetail.setWalletId(tbUserWallet.getId());
        tbUserWalletDetail.setUserId(tbUserWallet.getUserId());
        tbUserWalletDetail.setFromUser(fromUserId);
        tbUserWalletDetail.setBalance(tbUserWallet.getBalance());
        tbUserWalletDetailService.save(tbUserWalletDetail);
        return true;
    }


    @Override
    public void saveOrder() {
        //得到默认配置的时间
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("order_start_time");
        String daynum = "0";
        if (null != dictModelList && dictModelList.size() > 0) {
            daynum = dictModelList.get(0).getValue();
        }
        JDOrderRequest jdOrderRequest = new JDOrderRequest();
        jdOrderRequest.setPageNo(JDContants.order_pageNo);
        jdOrderRequest.setPageSize(JDContants.order_pageSize);
        //yyyyMMddHHmm
        String jdtime = DateUtil.getJDBeforeDate(Integer.valueOf(daynum));
        jdOrderRequest.setTime(jdtime);
        //type 订单时间查询类型(1：下单时间，2：完成时间，3：更新时间)
        jdOrderRequest.setType(1);
        List<JD_order> jd_orderList = JDOrderUtil.getOrders(jdOrderRequest);
        for (JD_order jd_order : jd_orderList) {
            Long order_id = jd_order.getOrderId();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_id", order_id);
            JD_order old_jd_order = this.getOne(queryWrapper);
            if (null == old_jd_order) {
                //保存订单
                String skugoods = jd_order.getSkuList();
                List<JD_order_sku> jd_positionList = JSON.parseArray(skugoods, JD_order_sku.class);
                for (JD_order_sku jd_order_sku : jd_positionList) {
                    jd_order_sku.setOrderId(jd_order.getOrderId());
                }
                this.save(jd_order);
            } else {


            }
        }
    }
}
